package com.itheima.mm.service.impl;

import com.css.tliasspringbootstarterautoconfigure.utils.JwtUtils;
import com.itheima.mm.dto.UserLoginDTO;
import com.itheima.mm.exception.AccountNotFoundException;
import com.itheima.mm.mapper.UserMapper;
import com.itheima.mm.pojo.User;
import com.itheima.mm.service.UserService;
import com.itheima.mm.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Value("${mm.md5.salt}")
    private String salt;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String preMD5Password =userLoginDTO.getPassword();
        String password = userLoginDTO.getPassword();
        //加盐加密
        password= DigestUtils.md5DigestAsHex((password+salt).getBytes());
        userLoginDTO.setPassword(password);
        User user = userMapper.login(userLoginDTO);
        if(user==null){
            throw new AccountNotFoundException("账户或密码错误");
        }
        String username = user.getUsername();

        Map<String, Object> cliams = new HashMap<>();
        cliams.put("username",username);
        cliams.put("password",preMD5Password);
        //生成jwt
        String jwt = jwtUtils.generateJwt(cliams);
        Integer id = user.getId();

        return new UserLoginVO(id,jwt);

    }
}
